package com.fdb.basic.framework.core.validate;

import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;

/**
 * @description:简单bean校验工具类
 * 				校验带有JSR-303注解类的对象
 * @date:2019年1月20日 下午12:35:23
 * @author:hengyh
 */
public class SimpleJSR303Validator {

	
	public static Set<ConstraintViolation<Object>> validate(Object bean) {
		return validator.validate(bean);
	}
	
	public static void validateAndThrow(Object bean) {	
		defaultConverter.apply(validator.validate(bean))
		.ifPresent(e -> {
			throw new IllegalArgumentException(e);
		});
	}
	
	static final Validator validator = Validation.byProvider(HibernateValidator.class)
			.configure().failFast(false).messageInterpolator(new ParameterMessageInterpolator())
			.buildValidatorFactory().getValidator();
	
	static final Function<Set<ConstraintViolation<Object>>, Optional<String>> defaultConverter = 
			cvs -> cvs.stream()
			.map(c -> new StringBuilder("参数：").append(c.getPropertyPath().toString()).append(c.getMessage())
					.append(",当前值:").append(c.getInvalidValue()))
			.reduce(StringBuilder::append)
			.map(StringBuilder::toString);
	
}
